<?php

namespace frontend\modules\shop\models;

use Yii;
use common\models\shop\ShopCart;

/**
 * 加入购物车模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartForm extends \common\base\Model {

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var integer SPUID
     */
    public $product_id;

    /**
     * @var integer SKUID
     */
    public $goods_id;

    /**
     * @var integer 数量
     */
    public $nums;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['product_id', 'goods_id', 'nums'], 'required'],
            [['user_id', 'product_id', 'goods_id', 'nums'], 'integer'],
        ];
    }

    /**
     * 加入购物车
     * @return boolean
     */
    public function add() {
        if (!$this->validate()) {
            return $this->dumpError('加入失败');
        }
        $model = ShopCart::findOrNew([
            'user_id' => $this->user_id,
            'product_id' => $this->product_id,
            'goods_id' => $this->goods_id,
            'deleted_at' => 0,
        ]);
        $model->num = intval($model->num) + $this->nums;
        $model->status = ShopCart::STATUS_CHECKED;
        if (!$model->save()) {
            return $this->dumpError($model->getErrorMsg(), false);
        }
        $nums = ShopCart::findActive()->andWhere(['user_id' => $this->user_id])->sum('num');
        return intval($nums);
    }

}
